<template>
  <!-- 需校验表单 -->
  <a-form-model v-if="isValidate" ref="ruleForm" :model="form" :rules="validRules" :labelCol="formGrid.labelCol"
    :wrapperCol="formGrid.wrapperCol">
    <base-form v-bind="$attrs" v-on="$listeners" :formList="formList" :form="form" @getPostInfo="getPostInfo">
      <!-- 插槽 -->
      <template v-for="item in formList" v-slot:[item.keyName]="scoped">
        <slot v-if="item.slot" :name="item.keyName" v-bind="scoped" />
      </template>
    </base-form>
  </a-form-model>
  <!-- 普通表单 -->
  <base-form ref="ruleForm" v-else v-bind="$attrs" v-on="$listeners" :formList="formList" :form="form"
    @getPostInfo="getPostInfo">
    <!-- 插槽 -->
    <template v-for="item in formList" v-slot:[item.keyName]="scoped">
      <slot v-if="item.slot" :name="item.keyName" v-bind="scoped" />
    </template>
  </base-form>
</template>

<script>
import BaseForm from '@/components/CustomForm/BaseForm' // 自定义表单

export default {
  name: 'CustomForm',
  inheritAttrs: false,
  components: {
    BaseForm
  },
  props: {
    // 是否校验
    isValidate: {
      type: Boolean,
      default: () => false
    },
    // 表单
    form: {
      type: Object,
      default: () => null
    },
    // 表单组件列表
    formList: {
      type: Array
    },
    // 表单校验规则
    rules: {
      type: [Object],
      default: () => { }
    },
    // 表单label和wraper栅格
    formGrid: {
      type: [Object],
      default: () => {
        return {
          labelCol: { span: 6 },
          wrapperCol: { span: 18 }
        }
      }
    }
  },
  computed: {
    // 校验表单规则，支持在formList直接写rule
    validRules() {
      let rules = {}
      // 遍历表单配置项，若有表单规则，则添加表单校验规则到规则枚举列表
      for (let item of this.formList) {
        if (item.rule) {
          rules[item.keyName] = item.rule
        }
      }
      return Object.assign({}, this.rules, rules)
    },
    // transForm: {
    //   get: function () {
    //     return this.form
    //   },
    //   set: function (val) {
    //     for (let item of this.formList) {
    //       const keyList = item.keyName.split('.')
    //       for (let key of keyList) {
    //         val[key] = item.rule
    //       }
    //     }
    //     this.$set()
    //   }
    // }
  },
  methods: {
    // 校验表单
    validate(callback) {
      this.$refs.ruleForm.validate((valid) => {
        callback && callback(valid)
      })
    },
    // 校验表单
    validateField(name, callback) {
      this.$refs.ruleForm.validateField(name, (valid) => {
        callback && callback(valid)
      })
    },
    // 清除校验
    clearValidate(arr) {
      this.$refs.ruleForm.clearValidate(arr)
    },
    /**
     * @description:获取当前选中的岗位数据
     */
    getPostInfo(data) {
      this.$emit("getPostInfo", data)
    }
  }
}
</script>
